package com.suliao.common.util;

import cn.hutool.core.codec.Base62;
import cn.hutool.crypto.SecureUtil;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * @author ：M1nG
 * @date ：Created in 2020/11/12 10:31
 * @description： 私有加密解密工具
 * @version: 1.0
 */
@Component
@NoArgsConstructor
public class CryPtoUtil {

    private String key = SecureUtil.md5("M1nG");
    private Boolean b = true;

    /**
     * 加密
     *
     * @return ciphertext
     */
    public String encrypt(String text) {
        String s = getCutString(this.key, 10, this.b) + Base62.encode(text) + getCutString(key, 10, !b);
        String ciphertext = new StringBuilder(s).reverse().toString();
        return ciphertext;
    }

    /**
     * 解密
     *
     * @return text
     */
    public String decrypt(String ciphertext) {
        String s1 = new StringBuilder(ciphertext).reverse().toString();
        String substring = s1.substring(10, s1.length() - 10);
        String text = Base62.decodeStr(substring);
        return text;
    }

    /**
     * 切割String
     *
     * @param str
     * @param size 获取的数量
     * @param rule true 正序 false
     * @return
     */
    public static String getCutString(String str, int size, boolean rule) {
        String[] split = str.split("");
        StringBuilder sb = new StringBuilder();
        if (rule) {
            for (int i = 0; i < split.length; i++) {
                sb.append(split[i]);
                if (sb.length() == size) {
                    break;
                }
            }
        } else {
            for (int i = split.length - 1; i >= 0; i--) {
                sb.append(split[i]);
                if (sb.length() == size) {
                    break;
                }
            }
        }
        return sb.toString();
    }


}
